package com.kcsoft.interceptor;

import com.kcsoft.utils.JwtUtil;
import com.kcsoft.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8082"); // 或 *（生产环境需明确域名）
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true"); // 如果需要携带 Cookie

        // 放行 OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String requestURI = request.getRequestURI();

        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            // 获取用户角色
            Integer role = (Integer) claims.get("role");

            // 检查路径权限
            if (isAuthorized(requestURI, role)) {
                ThreadLocalUtil.set(claims); // 将用户信息存储到 ThreadLocal
                return true;
            } else {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403 Forbidden
                return false;
            }
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }

    private boolean isAuthorized(String requestURI, Integer role) {
        // 定义路径权限规则
        if (requestURI.startsWith("/admin/")) {
            return role == 0; // 只有 role=0 可以访问 /admin/**
        } else if (requestURI.startsWith("/teacher/")) {
            return role <= 1; // 只有 role=1 可以访问 /teacher/**
        }
        // 默认不匹配的路径不进行权限校验
        return true;
    }
}
